package daoImp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import util.DateUtil;

import dao.NewsKeywordsDAO;

public class NewsKeywordsDAOImp implements NewsKeywordsDAO{
	private static NewsKeywordsDAOImp uniqueInstance = new NewsKeywordsDAOImp();
	private ConnectionPool pool = ConnectionPool.getInstance();
	public static NewsKeywordsDAO getInstance() {
		return uniqueInstance;
	}

	private NewsKeywordsDAOImp() {
	}

	public Map<String, Integer> getFrequencyByTrend(String trend, Date date) {
		String sql = null;
		Map<String, Integer> frequency = new HashMap<String, Integer>();
		try {
			Connection connection;
			try {
				connection = pool.getConnection();
			} catch (Exception e) {
				e.printStackTrace();
				return frequency;
			}
			Statement stmt = connection.createStatement();
			String dateStr = DateUtil.getNewsDateStr(date);
			trend = trend.replaceAll("'", "\\\\'").replaceAll("\\)", "\\\\)").replaceAll("\\(", "\\\\(");
			sql = "select * from newsKeywords where trend = '" + trend + "' and date = '" + dateStr +"';";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String word = rs.getString(2);
				int num = rs.getInt(3);
				frequency.put(word,num);
			}
			pool.returnConnection(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return frequency;
	}
	
}
